package com.heyou.modules.product.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heyou.common.service.impl.CrudServiceImpl;
import com.heyou.modules.product.dao.CategoryDao;
import com.heyou.modules.product.dto.CategoryDTO;
import com.heyou.modules.product.entity.CategoryEntity;
import com.heyou.modules.product.service.CategoryService;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品三级分类
 *
 * @author liangsw liangsw@yeah.net
 * @since 1.0.0 2025-05-21
 */
@Service
public class CategoryServiceImpl extends CrudServiceImpl<CategoryDao, CategoryEntity, CategoryDTO> implements CategoryService {

    @Override
    public QueryWrapper<CategoryEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }

    /**
     * 分类树形信息
     * @return ist<CategoryDTO>
     */
    @Override
    public List<CategoryDTO> selectByTree() {
        // 1、查询所有的分类信息
        Map<String, Object> params = new HashMap<>();
        params.put("showStatus", "1");
        List<CategoryDTO> categoryDTOS = this.list(params);
        // 2、组装树形结构
        // 2.1 获取所有的一级分类
        return categoryDTOS.stream()
                .filter(entity -> entity.getParentCid().equals(0L))
                .peek(entity -> entity.setChildren(selectChildren(entity, categoryDTOS))).sorted((one, two) -> {
                    return ObjectUtil.isEmpty(one.getSort()) ? 0 : one.getSort() - (ObjectUtil.isEmpty(two.getSort()) ? 0 : two.getSort());
                }).collect(Collectors.toList());
    }

    public List<CategoryDTO> selectChildren(CategoryDTO categoryDTO, List<CategoryDTO> categoryDTOS) {
        return categoryDTOS.stream().filter(item -> {
            return item.getParentCid().equals(categoryDTO.getCatId());
        }).peek(item -> item.setChildren(selectChildren(item, categoryDTOS))).sorted((one, two) -> {
            return (ObjectUtil.isEmpty(one.getSort()) ? 0 : one.getSort()) - (ObjectUtil.isEmpty(two.getSort()) ? 0 : two.getSort());
        }).collect(Collectors.toList());
    }
}